package com.college.heyuhua.controller;

import com.college.heyuhua.entity.UserInfo;
import com.college.heyuhua.model.BBSInfo;
import com.college.heyuhua.model.FileModel;
import com.college.heyuhua.service.IFileService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.List;

/**
 * Created by 赵东坡 on 2019/1/27.
 * Time:17:08
 * 宇宙无敌赵牛逼，祈求永无bug
 */
@Controller
public class ShardController {

    @Autowired
    private IFileService iFileService;

    @RequestMapping("/getFileList")
    public String upload() {
        System.out.println("上传文件");
        List<FileModel> list = iFileService.getFileModelList();
        return "home";
    }


    @RequestMapping("/searchFile")
    public String searchFile(@RequestParam("filename") String filename,ModelMap map) {


        if(StringUtils.isEmpty(filename)) {
            return "redirect:/look";
        }
        FileModel fileModel = iFileService.searchFile(filename);
        if(fileModel == null) {
            fileModel = iFileService.getFileMode();
            long uid = fileModel.getUid();
            UserInfo userInfo = iFileService.getUserInfo(uid);
            List<BBSInfo> bbsInfoList = iFileService.getBBSListForFile(fileModel.getFid(),"filebbs");
            map.put("bbsInfoList",bbsInfoList);
            map.put("userInfo",userInfo);
            map.put("fileModel",fileModel);
            map.put("message","搜索的文件不存在");
        }

        System.out.println("uid:"+fileModel.getUid());

        UserInfo userInfo = iFileService.getUserInfo(fileModel.getUid());

        List<BBSInfo> bbsInfoList = iFileService.getBBSListForFile(fileModel.getFid(),"filebbs");
        map.put("bbsInfoList",bbsInfoList);
        map.put("userInfo",userInfo);
        map.put("fileModel",fileModel);
        return "home";
    }

    @RequestMapping("/look")
    public String look(ModelMap map){
        FileModel fileModel = iFileService.getFileMode();
        long uid = fileModel.getUid();
        UserInfo userInfo = iFileService.getUserInfo(uid);
        List<BBSInfo> bbsInfoList = iFileService.getBBSListForFile(fileModel.getFid(),"filebbs");
        map.put("bbsInfoList",bbsInfoList);
        map.put("userInfo",userInfo);
        map.put("fileModel",fileModel);
        return "home";
    }


    @PostMapping("/submitbbs")
    public void submitbbs(@RequestParam("bbscontent") String bbscontent,
                            @RequestParam("fid") String fid,
                            @RequestParam("uid") String uid,HttpServletResponse response){

        boolean flag = iFileService.submitbbs(bbscontent,fid,uid);
        System.out.println(flag?"成功":"失败");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html");
        PrintWriter writer = null;
        try{
            writer = response.getWriter();
        }catch (Exception e){
            System.out.println(e.getMessage());
        }
        if(flag == false) {
            writer.print("修改失败");
            writer.close();
            writer.flush();
        }
        writer.print("修改成功");
        writer.close();
        writer.flush();
    }



    @RequestMapping("/uploadfileforshard")
    public void uploadfileforshard(@RequestParam(value = "inputfile", required = false) MultipartFile inputfile,
                                   String filename, String fileshort, String filetype, HttpServletResponse response, HttpSession session){

        String fileName = inputfile.getOriginalFilename();
        BufferedOutputStream stream = null;
        String filepath="shard/src/main/resources/upload/";

        try {
            byte[] bytes = inputfile.getBytes();
            File files = new File(filepath, inputfile.getOriginalFilename());
            FileOutputStream fileOutputStream = new FileOutputStream(files);
            stream = new BufferedOutputStream(fileOutputStream);
            stream.write(bytes);
            stream.close();

            response.setContentType("text/html");
            response.setCharacterEncoding("utf-8");
            PrintWriter writer= null;
            try {
                writer = response.getWriter();
            } catch (IOException e) {
                e.printStackTrace();
            }

            FileModel shardinfo = new FileModel();
            shardinfo.setUid(1);
            shardinfo.setFilename(fileName);
            shardinfo.setFileurl(filepath+""+fileName);
            shardinfo.setFiletype(filetype);
            shardinfo.setFileshort(fileshort);

            boolean flag = iFileService.insertfileshard(shardinfo);

            if(!flag){
                writer.print("上传失败");
            }else{
                writer.print("成功");
            }
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



    @ResponseBody
    @RequestMapping("/download/filename/{filename}")
    public void download(@PathVariable(value = "filename") String filename,
                         HttpServletResponse res) {

        res.setHeader("content-type", "application/octet-stream");
        res.setContentType("application/octet-stream");
        res.setHeader("Content-Disposition", "attachment;filename=" + filename);
        byte[] buff = new byte[1024];
        BufferedInputStream bis = null;
        OutputStream os = null;
        try {
            os = res.getOutputStream();
            bis = new BufferedInputStream(new FileInputStream(new File("shard/src/main/resources/upload/"+filename)));
            int i = bis.read(buff);
            while (i != -1) {
                os.write(buff, 0, buff.length);
                os.flush();
                i = bis.read(buff);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
